package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@SuppressWarnings("all")
@RestController
@Slf4j
@RequestMapping("/order")
public class OrderController {

    @Autowired
    RestTemplate restTemplate;
    @Value("${server.port}")
    String serverPort;
    //private String url="http://localhost:8001/payment/";
    private String url="http://CLOUD-PAYMENT-SERVICE";
    @Autowired
    DiscoveryClient discoveryClient;
    @Autowired
    LoadBalancer loadBalancer;


    @GetMapping("/getPaymentById/{id}")
    public CommonResult<Payment>getPaymentById(@PathVariable Long id){
        log.info("****serverPort:"+serverPort);
        return restTemplate.getForObject(url+"/payment/getPaymentById/"+id,CommonResult.class);
    }

    @PostMapping("/save")
    public CommonResult<Payment>save(@RequestBody Payment payment){
        log.info("****serverPort:"+serverPort);
        return restTemplate.postForObject(url+"/payment/save",payment,CommonResult.class);
    }
    //返回对象为响应中数据转换成的对象,基本上可以理解为JSON
    @GetMapping("/getPaymentById2/{id}")
    public CommonResult<Payment>getPaymentById2(@PathVariable Long id){
        log.info("****serverPort:"+serverPort);
        ResponseEntity<CommonResult> responseEntity = restTemplate.getForEntity(url + "/payment/getPaymentById/" + id, CommonResult.class);
        if(responseEntity.getStatusCode().is2xxSuccessful()){
            log.info("responseEntity.getStatusCode():"+responseEntity.getStatusCode());
            log.info("responseEntity.getStatusCode().is2xxSuccessful():"+responseEntity.getStatusCode().is2xxSuccessful());
            return responseEntity.getBody();
        }else{
           return new CommonResult("操作失败","444");
        }
    }
    @GetMapping("/lb")
    public String lb(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        ServiceInstance instance = loadBalancer.instances(instances);
        log.info(instance.getUri()+"****");
        return restTemplate.getForObject(instance.getUri()+"/payment/lb",String.class);
    }

}
